//package com.xdxc.filter;
//
//
//
//import cn.hutool.jwt.Claims;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import java.io.IOException;
//import java.util.Date;
//import java.util.List;
//import java.util.stream.Collectors;
//
//public class JwtAuthenticationFilter extends OncePerRequestFilter {
//
//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
//            throws ServletException, IOException {
//        String token = request.getHeader("Authorization");
//
//        if (token != null && token.startsWith("Bearer ")) {
//            try {
//                // 解析 JWT
//                Claims claims = JWTUtil.extractAllClaims(token.substring(7));
//                if (claims.getExpiration().before(new Date())) {
//                    throw new RuntimeException("Token expired");
//                }
//
//                // 获取用户名和角色
//                String username = claims.getSubject();
//                List<String> roles = (List<String>) claims.get("roles");
//
//                // 创建 Authentication 对象
//                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                        username,
//                        null,
//                        roles.stream()
//                                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
//                                .collect(Collectors.toList())
//                );
//
//                // 设置到 SecurityContext
//                SecurityContextHolder.getContext().setAuthentication(authentication);
//            } catch (Exception e) {
//                // 返回 401 响应
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                response.getWriter().write("Invalid or expired token");
//                return;
//            }
//        }
//
//        // 继续处理请求
//        filterChain.doFilter(request, response);
//    }
//}